var app = getApp();
// pages/order/downline.js
Page({
  data: {
    itemData: {},
    userId: 0,
    paytype: 'weixin', //0线下1微信
    remark: '',
    cartId: 0,
    addrId: 0, //收货地址//测试--
    btnDisabled: false,
    // productData:[],
    address: {},
    total: 0,
    vprice: 0,
    vid: 0,
    addemt: 1,
    vou: [],
    orderId: 0,
    carts: [],
    baseUrl: app.d.ceshiUrl,
  },
  onLoad: function(options) {
    let carts = JSON.parse(options.carts);
    console.log('-----------')
    console.log(carts[0])
    let total = 0;
    for (let i = 0; i < carts.length; i++) {
      // total = total + carts[i].totalPrice + 100
      total = total + carts[i].totalPrice
      console.log(this.data.total)
    }

    var uid = app.d.userId;
    this.setData({
      cartId: options.cartId,
      userId: uid,
      carts: carts,
      total:total,
      // total: parseFloat((total + 20 - 120).toFixed(2)),
    });
    // this.loadProductDetail();
  },
  onShow:function(){
    var that=this
    var carts = that.data.carts
   
    let total = 0;
    for (let i = 0; i < carts.length; i++) {
      // total = total + carts[i].totalPrice + 100
      total = total + carts[i].totalPrice
      console.log(this.data.total)
    }

    // var uid = app.d.userId;
    // this.setData({
    //   cartId: options.cartId,
    //   userId: uid,
    //   carts: carts,
    //   total: total,
    //   // total: parseFloat((total + 20 - 120).toFixed(2)),
    // });
  },
  // loadProductDetail:function(){
  //   var that = this;
  //   wx.request({
  //     url: app.d.ceshiUrl + '/Api/Payment/buy_cart',
  //     method:'post',
  //     data: {
  //       cart_id: that.data.cartId,
  //       uid: that.data.userId,
  //     },
  //     header: {
  //       'Content-Type':  'application/x-www-form-urlencoded'
  //     },
  //     success: function (res) {
  //       //that.initProductData(res.data);
  //       var adds = res.data.adds;
  //       if (adds){
  //         var addrId = adds.id;
  //         that.setData({
  //           address: adds,
  //           addrId: addrId
  //         });
  //       }
  //       that.setData({
  //         addemt: res.data.addemt,
  //         productData:res.data.pro,
  //         total: res.data.price,
  //         vprice: res.data.price,
  //         vou: res.data.vou,
  //       });
  //       //endInitData
  //     },
  //   });
  // },

  remarkInput: function(e) {
    this.setData({
      remark: e.detail.value,
    })
  },

  //选择优惠券
  getvou: function(e) {
    var vid = e.currentTarget.dataset.id;
    var price = e.currentTarget.dataset.price;
    var zprice = this.data.vprice;
    var cprice = parseFloat(zprice) - parseFloat(price);
    this.setData({
      total: cprice,
      vid: vid
    })
  },

  //微信支付
  createProductOrderByWX: function(e) {
    this.setData({
      paytype: 'weixin',
    });

    this.createProductOrder();
  },

  //线下支付
  createProductOrderByXX: function(e) {
    this.setData({
      paytype: 'cash',
    });
    wx.showToast({
      title: "线下支付开通中，敬请期待!",
      duration: 3000
    });
    return false;
    this.createProductOrder();
  },

  //确认订单
  createProductOrder: function() {
    this.setData({
      btnDisabled: false,
    })
    // if (!this.data.addrId || this.data.addrId=="undefined"){
    //   wx.showToast({
    //     title: '请填写好收货地址再提交!',
    //     duration:3000
    //   })
    //   return false;
    // }
    //创建订单
    var that = this;
    wx.request({
      url: app.d.ceshiUrl + '/transaction/StoreCartMgrAction!submit',
      method: 'post',
      header: app.globalData.header,
      success: function(res) {
        // console.log('createProductOrder')
        // console.log(res)
        var data = res.data;
        if (data.success == 'true') {
          //创建订单成功
          var order_id = data.orderFormId;
          that.setData({
            orderId: order_id
          });
          wx.showModal({
            title: '提示',
            content: '是否确认付款?',
            success: function (res) {
              if (res.confirm) {
                that.dopay(order_id);
              } else {
                wx.showToast({
                  title: "已下单,请付款!",
                  icon: 'loading',
                  duration: 2000
                });
                return
              }
            }
          })
         

          // 根据返回状态 选择支付方式  暂时不能删除


          // if (data.arr.pay_type == 'cash') {
          //   wx.showToast({
          //     title: "请自行联系商家进行发货!",
          //     duration: 3000
          //   });
          //   return false;
          // }
          // if (data.arr.pay_type == 'weixin') {
          //   //微信支付
          //   that.wxpay(data.arr);
          // }
        } else {
          wx.showToast({
            title: "去代付款处付款!",
            duration: 2500
          });
        }

      },
      fail: function(e) {
        wx.showToast({
          title: '网络异常！',
          duration: 2000
        });
      },
    })
  },
  dopay: function(e) {
    var that = this;
    console.log(app.globalData.openId)
    wx.request({
      // url: app.d.ceshiUrl + '/transaction/OrderFormMgrAction!wxPay',
      url: 'https://www.lh1717.com/Wxzf/Smhpay',
      // url: 'http://192.168.1.115:8080/Wxzf/Smhpay',
      data: {
        "OPEN_ID": app.globalData.openId,
        // "TRADE_NO": that.data.orderId,
        "TRADE_NO": "156494" + that.data.orderId,
        "MONEY":1
      },
      method: 'GET', // OPTIONS, GET, HEAD, POST, PUT, DELETE, TRACE, CONNECT
      header: app.globalData.header,
      success: function(res) {
        var order = res.data;
        console.log('dopay')
        
        console.log(order.nonce_str)
        console.log(order.timeStamp)
        console.log(order.prepay_id)
        console.log(order.paySign)
       
        wx.requestPayment({
           
          timeStamp: order.timeStamp,
          nonceStr: order.nonce_str,
          package: "prepay_id=" + order.prepay_id,
          signType: 'MD5',
          paySign: order.paySign,

          success: function (res) {
            console.log(res)
            console.log("requestPayment")
            wx.showToast({
              title: '支付成功!',
            })

          },
          fail: function (res) {
            console.log(res)
            console.log("requestPaymentfail")
            wx.showToast({
              title: res.err_desc,
              duration: 3000
            })
          }
        })
        // if (res.data.success == 'true') {
        //   thst.wxpay()
        //   // wx.showToast({
        //   //   title: '支付成功!',

        //   // });
        //   console.log('zhifuchengg ')
        //   wx.navigateTo({
        //     url: '/pages/user/user',
        //   })
        // } else {
        //   wx.showToast({
        //     title: res.data.err,
        //     duration: 2000
        //   });
        // }
      },
      fail: function() {
        // fail
        wx.showToast({
          title: '网络异常！',
          duration: 30000
        });
      }
    })
  },

  //调起微信支付
  wxpay: function(order) {
    var that = this;
    wx.request({
      url: app.d.ceshiUrl + '/Api/Pay/dowxpay',
      data: {
        order_id: order.order_id,
        order_sn: order.order_sn,
        uid: that.data.userId,
      },
      method: 'POST', // OPTIONS, GET, HEAD, POST, PUT, DELETE, TRACE, CONNECT
      header: app.globalData.header,
      success: function(res) {
        if (res.data.status == 1) {
          var order = res.data.success;
          wx.requestPayment({
            timeStamp: order.timeStamp,
            nonceStr: order.nonceStr,
            package: order.package,
            signType: 'MD5',
            paySign: order.paySign,
            success: function(res) {
              wx.showToast({
                title: '支付成功!',
              })

            },
            fail: function(res) {
              wx.showToast({
                title: res,
                duration: 3000
              })
            }
          })
        } else {
          wx.showToast({
            title: res.data.err,
            duration: 2000
          });
        }
      },
      fail: function() {
        // fail
        wx.showToast({
          title: '网络异常！',
          duration: 30000
        });
      }
    })
  },

});